package gu.sql2java.manager;

import java.util.List;

import gu.sql2java.BaseBean;
import gu.sql2java.TableListener;
import gu.sql2java.TableListener.Adapter;
import gu.sql2java.exception.DaoException;
import gu.sql2java.exception.RuntimeDaoException;

/**
 * abstract implementation of foreign key listener for DEELTE RULE
 * @author guyadong
 *
 * @param <FB> bean for foreign table 
 * @param <B> bean for self table
 */
abstract class BaseForeignKeyListener<FB extends BaseBean,B extends BaseBean> extends TableListener.Adapter<FB>{
    protected BaseForeignKeyListener(){}
    /**
     * Retrieves the imported B beans that reference to FB bean <BR>
     * @param fb foreign table bean
     * @return empty list if not found imported beans
     */
    protected abstract List<B> getImportedBeans(FB fb);
    /**
     * do something on foreign table row removed for effected imported beans {@code effectBeans}
     * @param affectedBeans affected imported beans
     * @throws DaoException
     */
    protected abstract void onRemove(List<B> affectedBeans) throws DaoException;
    protected final InheritableThreadLocal<List<B>> importedBeans = new InheritableThreadLocal<List<B>>();
    @Override
    public void beforeDelete(FB bean){
        this.importedBeans.set(getImportedBeans(bean));
    }

    @Override
    public void afterDelete(FB bean){
        List<B> beans = this.importedBeans.get();
        if(null != beans){
            try {
				this.onRemove(beans);
			} catch (DaoException e) {
				throw new RuntimeDaoException(e);
			}
        }
    }
    @Override
    public void done() {
        // clear TLS variable
        importedBeans.remove();
    }
}

